<template>
	<view class="customer">
		<gyd-navbar back-color="#fff" :title="title"></gyd-navbar>

		<view class="content">
			<view class="region-name">{{region_name}}</view>

			<gyd-tabs :list="tabsList" @clickItem="changeTab"></gyd-tabs>

			<view class="search">
				<uni-search-bar v-model="params.keyword" placeholder="客户关键字" clearButton="none" cancelButton="none"
					@blur="search">
				</uni-search-bar>
			</view>

			<view class="customer-list">
				<view class="customer-item" v-for="(item,index) in list" :key="index">
					<checkbox-group class="checkbox-group" @change="toggleCustomer">
						<checkbox class="item-left" :value="item.id" :checked="item.checked" />
					</checkbox-group>
					<view class="avatar">
						<image :src="item.avatar" mode="aspectFill"></image>
					</view>
					<view class="item-right">
						<view class="name">客户名称：{{ item.customer_name }}</view>
						<view class="phone">联系人：{{ item.fullname }}</view>
						<view class="phone">联系电话：{{ item.mobile }}</view>
						<view class="address">客户地址：{{item.format_address}}</view>
					</view>
				</view>

				<view class="empty-data" v-if="list.length===0 && current===0">本区域暂未添加客户</view>
				<view class="empty-data" v-if="list.length===0 && current===1">该店铺暂未绑定客户</view>
			</view>
		</view>

		<view class="footer">
			<view class="btn-group">
				<u-button class="btn" type="primary" size="large" block @click="saveInfo()">提交修改</u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const state = reactive({
		title: '区域客户',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		region_name: '',
		isMore: true,
		list: [],
		items: [],
		current: 0,
		tabsList: ['本区域客户', '非本区域客户'],
		params: {
			region_id: 0,
			keyword: '',
			type: 0,
			skip: 0
		}
	});

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		state.region_name = opt.region_name;
		if (opt.hasOwnProperty('id')) {
			console.log('传递参数', opt.id);
			state.params.region_id = opt.id;
		}
		getCustomerList();
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	})

	onReachBottom(() => {
		console.log('触底加载更多');
	})

	function getCustomerList() {
		if (!state.isMore) {
			util.showTip('没有更多了');
			return;
		}
		state.params.skip = state.list.length;
		request.get('merchant.storeregion/getCustomerList', state.params).then(res => {
			if (res.code == 1) {
				state.isMore = res.data.is_more;
				if (state.list.length == 0) {
					state.list = res.data.data;
				} else {
					state.list = state.list.concat(res.data.data);
				}
				initData();
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					mask: true
				})
			}
		})
	}

	function initData() {
		state.list.forEach(item => {
			item.id = item.id + ''; // 把 id 转成字符串
			state.items.forEach(sub => {
				if (item.id == sub) {
					console.log(item.customer_name + '选中');
					item.checked = true; // 更新所有子项状态
				}
			})
		});
	}

	function toggleCustomer(e) {
		state.items = e.detail.value;
		initData();
	}

	function changeTab(index) {
		state.current = index;
		state.current = e.currentIndex;
		state.params.type = e.currentIndex;
	}

	function search(e) {
		console.log('搜索', e);
		state.isMore = true;
		state.params.keyword = e.value;
		state.params.skip = 0;
		state.list = [];
		getCustomerList();
	}

	function saveInfo() {
		console.log('提交修改', state.items);
		if (state.items.length === 0) {
			util.showTip('请至少选择一个客户再提交');
			return;
		}

		let params = {
			id: state.params.region_id,
			customer_ids: ',' + state.items.join(',') + ',',
		}
		let url = 'merchant.storeregion/addCustomer';
		if (state.current === 0) {
			url = 'merchant.storeregion/delCustomer';
		}
		request.post(url, params).then(res => {
			console.log('保存结果', res);
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
			if (res.code == 1) {
				setTimeout(() => {
					search({
						value: ''
					});
				}, 800);
			}
		})
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		region_name,
		detail,
		isMore,
		list,
		items,
		current,
		tabsList,
		params
	} = toRefs(state);
</script>

<style lang="scss">
	.customer {
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));

		.content {
			.region-name {
				text-align: left;
				font-size: 36rpx;
				font-weight: 800;
				color: $main-color;
				padding: 20rpx 20rpx 0 20rpx;
			}

			.search {
				margin: 0 0 20rpx 0rpx;
			}

			.customer-list {
				background: #fff;
				padding: 20rpx;

				.customer-item {
					display: flex;
					margin: 0 0 20rpx 0;

					.item-left {}

					.avatar {
						width: 140rpx;
						height: 140rpx;
						background-color: #F7F7FB;
						border-radius: $radius-circle;
						margin: 0 20rpx 0 0;

						image {
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}
					}

					.item-right {
						flex: 1;
						display: block;

						.name {
							font-size: 30rpx;
							color: $main-color;
						}

						.phone {}

						.address {}
					}
				}

				.empty-data {
					margin-bottom: $m24;
					padding: $m24;
					background-color: #fff;
					border-radius: $radius-16;
					text-align: center;
					align-items: center;
					justify-content: center;
				}
			}
		}

		.footer {
			position: fixed;
			/* 固定在底部 */
			bottom: 0;
			width: 100%;

			.btn-group {
				.btn {}
			}
		}
	}
</style>